/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package robotics.sandbox;

/**
 *
 * @author fallen
 */
import java.awt.*;
import java.awt.event.KeyEvent;
import javax.swing.*;
import java.awt.image.*;
import java.awt.color.*;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyListener;

public class GreyFrame extends JComponent {

    public static void drawFrame(final BufferedImage img) {
        drawFrame(img, true);
    }
    public static void drawFrame(final BufferedImage img, final boolean closeOnKey) {
        EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                final JFrame f = new JFrame();
                f.getContentPane().add(new GreyFrame(img));
                f.setVisible(true);
                f.setSize(img.getWidth() + 20, img.getHeight() + 40);

                if (closeOnKey) {
                    f.addKeyListener(new KeyAdapter() {

                        @Override
                        public void keyTyped(KeyEvent e) {
                            super.keyTyped(e);
                            f.setVisible(false);
                        }
                    });
                }
//                f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            }
        });
    }

    private int width;
    private int height;
    private Dimension size;
    private BufferedImage image;
    private String title;

    private GreyFrame(int width, int height, byte[] data) {
        this(width, height, data, null);
    }

    private GreyFrame(BufferedImage img) {
        image = img;
        this.width = img.getWidth();
        this.height = img.getHeight();
        size = new Dimension(width, height);
    }

    private GreyFrame(int width, int height, byte[] data, String title) {
        this.width = width;
        this.height = height;
        this.title = title;
        size = new Dimension(width, height);

        DataBufferByte dataBuffer = new DataBufferByte(data, data.length, 0);

        image = ImageOperations.mkImage(width, height, data);
    }

    private Graphics2D getBufferImageGraphics() {
        return image.createGraphics();
    }

    private BufferedImage getBufferImage() {
        return image;
    }

    @Override
    public Dimension getSize() {
        return size;
    }

    @Override
    public Dimension getPreferredSize() {
        return size;
    }

    @Override
    public void paint(Graphics g) {
        super.paint(g);
        if (image != null) {
            g.drawImage(image, 0, 0, this);
        }

        if (title != null) {
            g.setColor(Color.RED);
            g.drawString(title, 5, height - 5);
        }
    }
}
